#!/bin/bash
################################################################################
# File Name: auto_install_mysql.sh
# Version: V1.0
# Author: Brian Hsiung
# Created Time : 2021-05-16 20:17:23
# Description:  一键部署二进制mysql
# 1. 默认安装目录为/usr/local/mysql
# 2. 默认数据目录为/opt/mysql/data
# 3. 默认binlog日志目录为/opt/mysql/binlog
# 4. 默认慢日志目录为/opt/mysql/slowlog
# 5. 默认端口为3306
# 6. SERVERID为当前主机ip最后几位,以ens160为例,也有可能为eth0等其它网卡，
#    需要根据实际情况修改，ip addr命令即可查看
###############################################################################

basedir='/usr/local/mysql'
datadir='/opt/mysql/data'
binlogdir='/opt/mysql/binlog'
slowlogdir='/opt/mysql/slowlog'
# mysql运行状态
mysqlStatus=
# 临时密码
tPassword=

# 判断用户，目录及端口
function mysql_environment_check() {
    echo -e "\n==================== 检查本机安装Mysql的基本条件 ====================\n"
    # 判断用户是否为root
    if [ $(id -u) -ne 0 ]; then
        echo -e "Error: You must be root to run this script.\n"
        exit 1
    fi
    # 判断目录是否为空
    if [ -d $basedir ]; then
        if [ -n "`ls -A $basedir`" ]; then
            echo -e "Error: $basedir is not empty, please check.\n"
            exit 1
        fi
    fi
    if [ -d $datadir ]; then
        if [ -n "`ls -A $datadir`" ]; then
            echo -e "Error: $datadir is not empty, please check.\n"
            exit 1
        fi
    fi
    if [ -d $binlogdir ]; then
        if [ -n "`ls -A $binlogdir`" ]; then
            echo -e "Error: $binlogdir is not empty, please check.\n"
            exit 1
        fi
    fi
    if [ -d $slowlogdir ]; then
        if [ -n "`ls -A $slowlogdir`" ]; then
            echo -e "Error: $slowlogdir is not empty, please check.\n"
            exit 1
        fi
    fi
    # 判断服务器上是否有3306端口占用
    if [ "`netstat -lntp|awk '{print $4}'|grep 3306|awk -F: 'NR==1{print $2}'`" = "3306" ]; then
        echo "port 3306 is used by another mysql process."
        exit 1
    fi

    echo -e "\n==================== 所有条件均通过，可以安装二进制MySQL ====================\n"
}

function install_mysql() {
    # 卸载系统自带数据库 yum erase -y
    rpm -qa|grep mysql 2>/dev/null
    if [ $? -eq 0 ]; then
        rpm -qa|grep mysql|xargs rpm -e --nodeps
    fi
    rpm -qa|grep mariadb 2>/dev/null
    if [ $? -eq 0 ]; then
        rpm -qa|grep mariadb|xargs rpm -e --nodeps
    fi

    # 创建用户和组
    grep 'mysql' /etc/group >/dev/null 2>&1
    [ $? -eq 0 ] || groupadd mysql
    grep 'mysql' /etc/passwd >/dev/null 2>&1
    [ $? -eq 0 ] || useradd -s /sbin/nologin -g mysql -M mysql

    # 解压
    echo -e "\nUnpacking the package, Please wait a minute .......\n"
    tar -zxf mysql*.tar.gz > /dev/null

    # 创建目录并授权
    mkdir -p $basedir $datadir $binlogdir $slowlogdir
    mv ./mysql-*x86_64/* $basedir
    chown mysql:mysql -R $basedir $datadir $binlogdir $slowlogdir

    # server-id，这里以ens160为例,也有可能为eth0等其它网卡，需要根据实际情况修改，ip addr命令即可查看
    SERVERID=`ifconfig ens160|grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}'|head -n1|cut -d . -f4`
    echo -e "\n==================== server-id = $SERVERID Mysql Is Installing ... ====================\n"

    if [ -s /etc/my.cnf ];then
        mv /etc/my.cnf /etc/my.cnf.bak
    fi
cat > /etc/my.cnf << EOF
[client]
port = 3306
socket=/tmp/mysql.sock

[mysqld]
port = 3306
user = mysql
server-id = $SERVERID
skip-name-resolve
max_connections = 4000
lower_case_table_names = 1
default_time_zone = +8:00
default_storage_engine = InnoDB
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET collation_connection = utf8mb4_general_ci'
init_connect='SET NAMES utf8mb4'

basedir=$basedir
datadir=$datadir
socket=/tmp/mysql.sock
log-error=$datadir/mysql-error.log
pid-file=$datadir/mysqld.pid
log-bin=$binlogdir/mysql3306-bin

binlog_format = ROW
expire_logs_days = 91

transaction-isolation = READ-COMMITTED

sql-mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
EOF

    # 初始化数据库--defaults-file=/etc/my.cnf --initialize-insecure初始化没密码
    $basedir/bin/mysqld --user=mysql --basedir=$basedir --datadir=$datadir --initialize 
    cp $basedir/support-files/mysql.server /etc/init.d/mysqld
    chmod 700 /etc/init.d/mysqld
    chkconfig --add mysqld
    chkconfig mysqld on

    #临时密码
    tPassword=$(grep 'A temporary password' $datadir/mysql-error.log|awk '{print $NF}')
    echo $tPassword > ./tPassword
    
    service mysqld start

    echo "MYSQL_HOME=$basedir" >> /etc/profile
    echo "PATH=\$PATH:\$MYSQL_HOME/bin" >> /etc/profile
    source /etc/profile
    echo -e "\n==================== MySQL install completed ====================\n"
}

function check_install() {
    if [ -s $basedir/bin/mysql ] && [ -s $basedir/bin/mysqld_safe ] && [ -s /etc/my.cnf ] && [ `netstat -lntp| awk '{ print $4}' |grep '3306'|awk  -F: '{ print $4}'` = "3306" ]; then
        mysqlStatus="OK"
    else
        echo -e "\nError: MySQL install failed, please view $datadir/mysql-error.log for more information\n"
    fi
}

function init_password() {
    if [ "$mysqlStatus" = "OK" ] && [ -n "$tPassword" ]; then
        # 生成随机20位包含大小写字母和数字的密码
        rootPassword=$(head /dev/urandom|tr -dc '0-9a-zA-Z'|cut -c -20)
        adminPassword=$(head /dev/urandom|tr -dc '0-9a-zA-Z'|cut -c -20)
        echo "rootPassword: $rootPassword" >> ./myPassword
        echo "adminPassword: $adminPassword" >> ./myPassword
        # 修改root密码
        $basedir/bin/mysqladmin -uroot -p"$tPassword" password "$rootPassword" 2>/dev/null
        if [ $? -ne 0 ]; then
            echo -e "==================== Change root password Failed...... ====================\n"
            exit 1
        fi
        # 添加管理员admin账号并授权
        $basedir/bin/mysql -uroot -p"$rootPassword" -e "create user 'admin'@'%' identified by '${adminPassword}';GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, PROCESS, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER ON *.* TO 'admin'@'%' WITH GRANT OPTION;flush privileges;" 2>/dev/null
        if [ $? -ne 0 ]; then
            echo -e "==================== User admin Add Failed...... ====================\n"
            exit 1
        fi
        echo -e "==================== View Password In ./myPassword ...... ====================\n "
    else
        echo -e "\n==================== MySQL Is Not Running Or Can Not Find Init Password... ====================\n"
    fi
}

echo -e "\n==================== Install MySQL on Redhat/CentOS 7 Linux ====================\n"
DIR=`dirname $0`
cd $DIR
mysql_environment_check
install_mysql
check_install
init_password